import React, { useState, useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
import { 
  Card, 
  List, 
  Avatar, 
  Tag, 
  Button, 
  Input, 
  Select, 
  Space, 
  Pagination,
  Empty,
  Spin,
  Row,
  Col,
  Progress
} from 'antd';
import { 
  CalendarOutlined, 
  PlusOutlined, 
  SearchOutlined,
  UserOutlined,
  ClockCircleOutlined,
  EnvironmentOutlined,
  TeamOutlined
} from '@ant-design/icons';
import { ACTIVITY_STATUS } from '../../constants';
import { Activity } from '../../types';
import './Activities.scss';

const { Search } = Input;
const { Option } = Select;

const Activities: React.FC = () => {
  const navigate = useNavigate();
  const [loading, setLoading] = useState(false);
  const [activities, setActivities] = useState<Activity[]>([]);
  const [currentPage, setCurrentPage] = useState(1);
  const [total, setTotal] = useState(0);
  const [searchKeyword, setSearchKeyword] = useState('');
  const [statusFilter, setStatusFilter] = useState('all');

  // 模拟数据
  const mockActivities: Activity[] = [
    {
      id: '1',
      title: '校园编程大赛',
      description: '面向全校学生的编程竞赛，展示你的编程技能',
      organizer: { id: '1', username: '计算机学院', email: 'cs@university.edu', role: 'teacher' },
      startTime: '2024-01-20T09:00:00Z',
      endTime: '2024-01-20T17:00:00Z',
      location: '教学楼A101',
      maxParticipants: 100,
      currentParticipants: 45,
      status: 'upcoming',
      createdAt: '2024-01-10T10:00:00Z',
    },
    {
      id: '2',
      title: '英语角活动',
      description: '每周英语角，提高口语表达能力',
      organizer: { id: '2', username: '外语学院', email: 'foreign@university.edu', role: 'teacher' },
      startTime: '2024-01-22T19:00:00Z',
      endTime: '2024-01-22T21:00:00Z',
      location: '图书馆三楼',
      maxParticipants: 50,
      currentParticipants: 23,
      status: 'upcoming',
      createdAt: '2024-01-12T14:00:00Z',
    },
    {
      id: '3',
      title: '篮球友谊赛',
      description: '学院间篮球友谊赛，增进同学间的友谊',
      organizer: { id: '3', username: '体育部', email: 'sports@university.edu', role: 'teacher' },
      startTime: '2024-01-18T14:00:00Z',
      endTime: '2024-01-18T16:00:00Z',
      location: '体育馆',
      maxParticipants: 20,
      currentParticipants: 20,
      status: 'ongoing',
      createdAt: '2024-01-08T09:00:00Z',
    },
    {
      id: '4',
      title: '学术讲座：人工智能的发展趋势',
      description: '邀请业界专家分享AI领域的最新发展',
      organizer: { id: '4', username: '人工智能学院', email: 'ai@university.edu', role: 'teacher' },
      startTime: '2024-01-15T14:00:00Z',
      endTime: '2024-01-15T16:00:00Z',
      location: '学术报告厅',
      maxParticipants: 200,
      currentParticipants: 180,
      status: 'ended',
      createdAt: '2024-01-05T10:00:00Z',
    },
  ];

  useEffect(() => {
    loadActivities();
  }, [currentPage, searchKeyword, statusFilter]);

  const loadActivities = async () => {
    setLoading(true);
    try {
      // 模拟API调用
      await new Promise(resolve => setTimeout(resolve, 500));
      
      let filteredActivities = mockActivities;
      
      // 按状态过滤
      if (statusFilter !== 'all') {
        filteredActivities = mockActivities.filter(activity => activity.status === statusFilter);
      }
      
      // 按关键词搜索
      if (searchKeyword) {
        filteredActivities = filteredActivities.filter(activity => 
          activity.title.includes(searchKeyword) || 
          activity.description.includes(searchKeyword) ||
          activity.organizer.username.includes(searchKeyword)
        );
      }
      
      // 按开始时间排序
      filteredActivities.sort((a, b) => 
        new Date(a.startTime).getTime() - new Date(b.startTime).getTime()
      );
      
      setActivities(filteredActivities);
      setTotal(filteredActivities.length);
    } catch (error) {
      console.error('加载活动失败:', error);
    } finally {
      setLoading(false);
    }
  };

  const handleActivityClick = (activityId: string) => {
    navigate(`/activities/${activityId}`);
  };

  const handleCreateActivity = () => {
    navigate('/activities/create');
  };

  const handleJoinActivity = (activityId: string, e: React.MouseEvent) => {
    e.stopPropagation();
    // 处理参加活动逻辑
    console.log('参加活动:', activityId);
  };

  const handleSearch = (value: string) => {
    setSearchKeyword(value);
    setCurrentPage(1);
  };

  const handleStatusFilterChange = (value: string) => {
    setStatusFilter(value);
    setCurrentPage(1);
  };

  const getStatusColor = (status: string) => {
    const colors = {
      upcoming: 'blue',
      ongoing: 'green',
      ended: 'default',
    };
    return colors[status as keyof typeof colors] || 'default';
  };

  const formatDateTime = (dateString: string) => {
    const date = new Date(dateString);
    return date.toLocaleString('zh-CN', {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit',
      hour: '2-digit',
      minute: '2-digit',
    });
  };

  const getParticipantPercentage = (current: number, max: number) => {
    return Math.round((current / max) * 100);
  };

  return (
    <div className="activities-page">
      <div className="page-header">
        <div className="header-left">
          <h1>活动中心</h1>
          <p>发现精彩活动，丰富校园生活</p>
        </div>
        <div className="header-right">
          <Button 
            type="primary" 
            icon={<PlusOutlined />}
            onClick={handleCreateActivity}
          >
            创建活动
          </Button>
        </div>
      </div>

      {/* 筛选和搜索 */}
      <Card className="filter-card">
        <div className="filter-content">
          <Space size="middle" wrap>
            <Search
              placeholder="搜索活动..."
              allowClear
              onSearch={handleSearch}
              style={{ width: 300 }}
              prefix={<SearchOutlined />}
            />
            <Select
              value={statusFilter}
              onChange={handleStatusFilterChange}
              style={{ width: 120 }}
            >
              <Option value="all">全部状态</Option>
              <Option value="upcoming">即将开始</Option>
              <Option value="ongoing">进行中</Option>
              <Option value="ended">已结束</Option>
            </Select>
          </Space>
        </div>
      </Card>

      {/* 活动列表 */}
      <Card className="activities-card">
        <Spin spinning={loading}>
          {activities.length > 0 ? (
            <List
              dataSource={activities}
              renderItem={(activity) => (
                <List.Item
                  className="activity-item"
                  onClick={() => handleActivityClick(activity.id)}
                >
                  <List.Item.Meta
                    avatar={<Avatar icon={<CalendarOutlined />} />}
                    title={
                      <div className="activity-title">
                        <span>{activity.title}</span>
                        <Tag color={getStatusColor(activity.status)}>
                          {ACTIVITY_STATUS[activity.status as keyof typeof ACTIVITY_STATUS]}
                        </Tag>
                      </div>
                    }
                    description={
                      <div className="activity-content">
                        <p className="activity-description">{activity.description}</p>
                        
                        <Row gutter={[16, 8]} className="activity-info">
                          <Col xs={24} sm={12} md={6}>
                            <div className="info-item">
                              <UserOutlined />
                              <span>主办方：{activity.organizer.username}</span>
                            </div>
                          </Col>
                          <Col xs={24} sm={12} md={6}>
                            <div className="info-item">
                              <ClockCircleOutlined />
                              <span>开始：{formatDateTime(activity.startTime)}</span>
                            </div>
                          </Col>
                          <Col xs={24} sm={12} md={6}>
                            <div className="info-item">
                              <EnvironmentOutlined />
                              <span>地点：{activity.location}</span>
                            </div>
                          </Col>
                          <Col xs={24} sm={12} md={6}>
                            <div className="info-item">
                              <TeamOutlined />
                              <span>参与：{activity.currentParticipants}/{activity.maxParticipants}</span>
                            </div>
                          </Col>
                        </Row>
                        
                        <div className="activity-footer">
                          <div className="participant-progress">
                            <Progress 
                              percent={getParticipantPercentage(activity.currentParticipants, activity.maxParticipants)}
                              size="small"
                              showInfo={false}
                            />
                            <span className="progress-text">
                              {activity.currentParticipants}/{activity.maxParticipants} 人参与
                            </span>
                          </div>
                          
                          {activity.status === 'upcoming' && activity.currentParticipants < activity.maxParticipants && (
                            <Button 
                              type="primary" 
                              size="small"
                              onClick={(e) => handleJoinActivity(activity.id, e)}
                            >
                              参加活动
                            </Button>
                          )}
                        </div>
                      </div>
                    }
                  />
                </List.Item>
              )}
            />
          ) : (
            <Empty 
              description="暂无活动"
              image={Empty.PRESENTED_IMAGE_SIMPLE}
            />
          )}
        </Spin>
        
        {total > 0 && (
          <div className="pagination-wrapper">
            <Pagination
              current={currentPage}
              total={total}
              pageSize={10}
              onChange={setCurrentPage}
              showSizeChanger={false}
              showQuickJumper
              showTotal={(total, range) => 
                `第 ${range[0]}-${range[1]} 条，共 ${total} 条`
              }
            />
          </div>
        )}
      </Card>
    </div>
  );
};

export default Activities;
